package org.sojex.photo.util;

import java.util.List;

import org.sojex.R;
import org.sojex.photo.bean.CookBean;
import org.sojex.photo.util.AsyncImageLoader.ImageCallback;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

public class GalleryAdapter extends ArrayAdapter<CookBean> {

	    private Gallery gallery;
	    private AsyncImageLoader asyncImageLoader;
	    Context context;
	    public GalleryAdapter(Context context, List<CookBean> bean, Gallery gallery) {
	        super(context, 0, bean);
	        this.context = context;
	        this.gallery = gallery;
	        asyncImageLoader = new AsyncImageLoader();
	    }

	    public View getView(int position, View convertView, ViewGroup parent) {
	        // Inflate the views from XML
	        View rowView = convertView;
	        ViewCache viewCache;
	        if (rowView == null) {
	            LayoutInflater inflater = LayoutInflater.from(context);
	            rowView = inflater.inflate(R.layout.photo_gallery_row, null);
	            viewCache = new ViewCache(rowView);
	            rowView.setTag(viewCache);
	        } else {
	            viewCache = (ViewCache) rowView.getTag();
	        }
	        CookBean bean = getItem(position);

	        // Load the image and set it on the ImageView
	        String imageUrl = bean.url;
	        ImageView imageView = viewCache.getImageView();
	        imageView.setTag(imageUrl);
	        Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl, new ImageCallback() {
	            public void imageLoaded(Drawable imageDrawable, String imageUrl) {
	                ImageView imageViewByTag = (ImageView) gallery.findViewWithTag(imageUrl);
	                if (imageViewByTag != null) {
	                    imageViewByTag.setImageDrawable(imageDrawable);
	                }
	            }
	        });
			if (cachedImage == null) {
				imageView.setImageResource(R.drawable.icon);
			}else{
				imageView.setImageDrawable(cachedImage);
			}
	        // Set the text on the TextView

	        return rowView;
	    }

}
